import _ from 'lodash'
import cache from '../utils/Cache.js'
import { shuffle, createRand, getIdByKey } from '../utils/utils.js'

const CACHENAME = 'drawCache'
const workersRaw = window.PHP.workers.map((w) => ({ ...w, img: w.img || '0.webp' }))
const MAXWINNER = window.PHP.MAXWINNER > 0 ? window.PHP.MAXWINNER : workersRaw.length // 最大中奖人数
const __workers = ref(_.cloneDeep(workersRaw))
const cacheData = window.PHP.isOpenCache ? cache.get(CACHENAME) : null
const _workersCache = cacheData?._workers
const _resultCache = cacheData?._result
const winnerCache = cacheData?.winner

export default function useHook() {
  const audio = new Audio()
  let timer = null
  const workers = ref(shuffle(workersRaw))
  const _workers = ref(_workersCache || __workers.value)
  const _result = ref(_resultCache || -1)
  const winner = ref(winnerCache || [])
  const currentWinner = ref()

  const busy = ref(false)

  const isEnd = computed(() => _workers.value.length <= 0 || winner.value.length >= MAXWINNER)
  const isShowWinner = computed(() => {
    return currentWinner.value && !busy.value
  })

  function playSound(type = 0) {
    if (type == 0) {
      audio.src = './music/start.mp3'
      audio.play()
      audio.loop = true
    }
    if (type == 1) {
      audio.src = './music/winner.mp3'
      audio.play()
      audio.loop = false
    }
  }

  function start() {
    if (isEnd.value || busy.value) return
    playSound()
    busy.value = true
    workers.value = shuffle(workers.value)
    timer = setInterval(() => {
      workers.value = shuffle(workersRaw)
    }, 100)
  }

  function stop() {
    if (isEnd.value || !busy.value) return
    playSound(1)
    clearInterval(timer)

    let _rand = createRand(_workers.value.length)
    _result.value = _rand

    const winnerItem = _workers.value[_result.value]
    winner.value.unshift({
      ...winnerItem,
    })

    currentWinner.value = winnerItem
    _workers.value.splice(_result.value, 1)
    _result.value = -1

    busy.value = false

    if (window.PHP.isOpenCache) {
      cache.set(CACHENAME, { _workers: _workers.value, _result: _result.value, winner: winner.value })
    }
  }

  function run() {
    busy.value ? stop() : start()
  }

  function clearCache() {
    cache.remove(CACHENAME)
  }

  return {
    workers,
    _workers,
    _result,
    winner,
    currentWinner,
    isShowWinner,
    busy,
    isEnd,
    start,
    stop,
    run,
    clearCache,
  }
}
